package com.wjw.cloud.controller;

import com.wjw.cloud.common.api.CommonResult;
import com.wjw.cloud.common.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Controller
@Api(tags = "FileController", description = "图片上传下载")
@RequestMapping(value = "/file")
public class FileController {

    @Value("${file.path}")
    private String filePath;

    @ApiOperation(value = "图片上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestParam("file") MultipartFile file)
    {
        log.info("图片上传开始 filename={}", file.getOriginalFilename());

        try {

            String newFilename = FileUtil.upload(file, filePath);

            return CommonResult.success("resources/" + newFilename);

        } catch (IOException e) {
            log.info("图片上传失败 e={}", e.getMessage());
            return CommonResult.failed();
        }
    }

}
